//
//  OpinionViewController.m
//  JiuLe
//
//  Created by 黄鑫 on 16/9/2.
//  Copyright © 2016年 Fine. All rights reserved.
//

#import "OpinionViewController.h"
#import "BaseDataRequest.h"
#import "ImageSelectView.h"
#import "PictureSelect.h"
#define MAX_LIMIT_NUMS 400

@interface OpinionViewController ()<UITextViewDelegate,ImageSelectViewDelegate,PictureSelectDelegate>
@property (weak, nonatomic) IBOutlet UITextView *textViewMain;
@property (weak, nonatomic) IBOutlet UIButton *btnInput;
@property (weak, nonatomic) IBOutlet ImageSelectView *selectImage;
@property (weak, nonatomic) IBOutlet UILabel *labSB;
@property (copy, nonatomic) void(^imageBlock)(UIImage *image);
@property (strong, nonatomic) PictureSelect *pictureSelect;
@property (strong, nonatomic) NSMutableArray *arrImage;

@end

@implementation OpinionViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"意见反馈";
    [self showNavgationWithLeftItemWithTitle:@"返回"];
    self.btnInput.enabled = NO;
    self.selectImage.delegate = self;
    self.labSB.text = [NSString stringWithFormat:@"%d/%d",MAX_LIMIT_NUMS,MAX_LIMIT_NUMS];
}


#pragma mark - UITextViewDelegate
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range
 replacementText:(NSString *)text
{
    NSString *comcatstr = [textView.text stringByReplacingCharactersInRange:range withString:text];
    
    NSInteger caninputlen = MAX_LIMIT_NUMS - comcatstr.length;
    
    if (caninputlen >= 0)
    {
        return YES;
    }
    else
    {
        NSInteger len = text.length + caninputlen;
        //防止当text.length + caninputlen < 0时，使得rg.length为一个非法最大正数出错
        NSRange rg = {0,MAX(len,0)};
        
        if (rg.length > 0)
        {
            NSString *s = [text substringWithRange:rg];
            
            [textView setText:[textView.text stringByReplacingCharactersInRange:range withString:s]];
            self.labSB.text = @"0/400";
        }
        return NO;
    }
    
}

- (void)textViewDidChange:(UITextView *)textView
{
    NSString  *nsTextContent = textView.text;
    NSInteger existTextNum = nsTextContent.length;
    
    if (existTextNum > MAX_LIMIT_NUMS)
    {
        //截取到最大位置的字符
        NSString *s = [nsTextContent substringToIndex:MAX_LIMIT_NUMS];
        
        [textView setText:s];
    }
    //不让显示负数
    self.labSB.text = [NSString stringWithFormat:@"%ld/%d",MAX(0,MAX_LIMIT_NUMS - existTextNum),MAX_LIMIT_NUMS];
}
- (void)textViewDidBeginEditing:(UITextView *)textView{
    if ([textView.text isEqualToString:@"请写下您的意见和建议，或遇到的问题，我们会尽快处理（10~400字以内）"]) {
        textView.text = @"";
        textView.textColor = [UIColor blackColor];
        self.btnInput.enabled = NO;
    }
}

- (void)textViewDidEndEditing:(UITextView *)textView{
    [self.textViewMain resignFirstResponder];
    if ([self.textViewMain.text isEqualToString:@""]) {
        self.textViewMain.text = @"请写下您的意见和建议，或遇到的问题，我们会尽快处理（10~400字以内）";
        textView.textColor = [UIColor grayColor];
        self.btnInput.enabled = NO;
    }
    if (self.textViewMain.text.length > 400 || self.textViewMain.text.length < 10) {
        if (self.textViewMain.text.length > 400) {
            self.textViewMain.text = [self.textViewMain.text substringToIndex:400];
            TIPSFORVIEW(@"输入字数大于400");
            self.btnInput.enabled = YES;
        }else{
            //self.textViewMain.text = @"请写下您的意见和建议，或遇到的问题，我们会尽快处理（10~400字以内）";
            //textView.textColor = [UIColor grayColor];
            TIPSFORVIEW(@"输入字数少于10");
            self.btnInput.enabled = NO;
        }
    }else{
        self.btnInput.enabled = YES;
    }
}

- (IBAction)inputAction:(id)sender {
    [SVProgressHUD showWithStatus:@"提交反馈..." maskType:SVProgressHUDMaskTypeClear];
    [[BaseDataRequest alloc] feedback:self.textViewMain.text imageArr:self.arrImage withBlock:^(id responseObject, NSString *status, NSError *error) {
        [SVProgressHUD dismiss];
        if([status isEqualToString:@"0"]){
            [self.navigationController popViewControllerAnimated:YES];
        }else{
            if (error != nil) {
                TIPSFORVIEW(@"请检测网络设置");
            }else{
                NSString *message = [responseObject objectForKey:@"message"];
                if ([message isEqualToString:@""]) {
                    TIPSFORVIEW(@"提交反馈失败");
                }else{
                    TIPSFORVIEW(message);
                }
            }
        }
    }];
}

#pragma mark - ImageSelectViewDelegate
- (void)selectPhoto:(void (^)(UIImage *image))block{
    [_textViewMain resignFirstResponder];
    _imageBlock = block;
    if(_pictureSelect == nil){
        _pictureSelect=[[PictureSelect alloc]initWithView:self];
        _pictureSelect.delegate = self;
    }
    [_pictureSelect changeIcon];
}

- (void)deletePhoto:(int)index{
    [_arrImage removeObjectAtIndex:index];
}

#pragma mark - PictureSelectDelegate
-(void)iconChooseFinish:(UIImage*)img{
    if (_imageBlock) {
        _imageBlock(img);
    }
    [SVProgressHUD showWithStatus:@"图片上传中..." maskType:SVProgressHUDMaskTypeClear];
    [[BaseDataRequest alloc] feedbackPicture:img withBlock:^(id responseObject, NSString *status, NSError *error) {
        [SVProgressHUD dismiss];
        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
        if ([status isEqualToString:@"0"]) {
            NSDictionary *dict = [responseObject objectForKey:@"result"];
            [self.arrImage insertObject:[dict objectForKey:@"fk_url"] atIndex:0];
            TIPSFORVIEW(@"上传图片成功");
        }else{
            if (error != nil) {
                TIPSFORVIEW(@"请检测网络设置");
            }else{
                //TIPSFORVIEW(@"上传图片失败");
            }
        }
    }];
}

#pragma mark - set/get
- (NSMutableArray *)arrImage{
    if (_arrImage == nil) {
        _arrImage = [NSMutableArray array];
    }
    return _arrImage;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end
